package org.example.booksmanagementsystem.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.example.booksmanagementsystem.constant.Constants;
import org.example.booksmanagementsystem.enums.ResultStatus;
import org.example.booksmanagementsystem.model.Result;
import org.example.booksmanagementsystem.model.UserInfo;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.Arrays;
import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private Long startTime;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        log.info("目标接口执行前");

        // true表示没有session创建新的session，false表示没有session直接返回
        HttpSession session = request.getSession(false);

        if(session==null){
            response.setStatus(401); //401表示认证为不通过
            return false;
        }

        //验证是否认证
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.SESSION_USER_KEY);
        if(userInfo==null){

//            Result result = new Result();
//            result.setStatus(ResultStatus.UNLOGIN);

            response.setStatus(401); //401表示认证为不通过
            return  false;

        }else if(userInfo.getId()<0){
//            Result result = new Result();
//            result.setStatus(ResultStatus.UNLOGIN);

            response.setStatus(401); //401表示认证为不通过
            return false;
        }

        // 记录用户浏览的时间--开始时间
        startTime = System.currentTimeMillis();

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        log.info("目标接口执行后");


        // 计时结束
        long duration = System.currentTimeMillis() - startTime;

        // 提取session
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.SESSION_USER_KEY);
        if(session!=null){
            log.info("用户Id{"+userInfo.getId()+"}"+"停留了["+duration + "]ms:");

            log.info("页面["+request.getRequestURI()+"],参数：["+getRequestParams(request)+"]");
        }

        startTime = System.nanoTime();

    }

    // 获取请求参数的方法
    private String getRequestParams(HttpServletRequest request) {
        Map<String, String[]> paramMap = request.getParameterMap();
        if (paramMap.isEmpty()) return "无参数";

        StringBuilder params = new StringBuilder();
        for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
            String paramName = entry.getKey();
            String[] values = entry.getValue();
            params.append(paramName)
                    .append("=")
                    .append(Arrays.toString(values))
                    .append("; ");
        }
        return params.toString().trim();
    }
}
